package com.zhoupu.integrated.library.controller;

import com.zhoupu.integrated.library.model.Book;
import com.zhoupu.integrated.library.repository.BookRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/books")
@Tag(name = "图书接口", description = "图书接口相关操作")
public class BookController {

    @Autowired
    private BookRepository bookRepository;

    @GetMapping
    @Operation(summary = "获取所有图书", description = "获取所有图书-全量车型")
    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    @PostMapping
    @Operation(summary = "新增图书", description = "新增图书数据")
    public Book createBook(@RequestBody Book book) {
        return bookRepository.save(book);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取图书详情", description = "根据ID获取图书详情")
    public Book getBookById(
            @Parameter(name = "id", description = "图书ID", required = true, in = ParameterIn.PATH)
            @PathVariable String id) {
        return bookRepository.findById(id).orElse(null);
    }

    @PutMapping("/{id}")
    @Operation(summary = "修改图书", description = "根据ID修改图书信息")
    public Book updateBook(@PathVariable String id, @RequestBody Book bookDetails) {
        Book book = bookRepository.findById(id).orElse(null);
        if (book != null) {
            book.setTitle(bookDetails.getTitle());
            book.setAuthor(bookDetails.getAuthor());
            book.setYearPublished(bookDetails.getYearPublished());
            return bookRepository.save(book);
        }
        return null;
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除图书", description = "根据ID删除图书")
    public void deleteBook(@PathVariable String id) {
        bookRepository.deleteById(id);
    }
}
